//
//  WZSignSettingController.m
//  WZEfengAndEtong
//
//  Created by wanzhao on 2016/10/8.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "WZSignSettingController.h"
#import "WZSignSettingCell.h"
#import "WZFacePerceptionController.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "CContactModel.h"
#import "CContactMgr.h"

#define MOBILESIGN_TYPE @"MOBILESIGN_TYPE"
#define MOBILESIGN_FACE_IDENTIFICATION @"MOBILESIGN_FACE_IDENTIFICATION"

@interface WZSignSettingController ()<UITableViewDelegate, UITableViewDataSource, UIActionSheetDelegate>

@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *sectionArray;
@property (strong, nonatomic) NSMutableArray *itemArray;
@property (assign, nonatomic) NSInteger signItemCount;
@property (copy,   nonatomic) NSString *signType;
@property (nonatomic, strong) CContactModel *currentUser;
@property (copy,   nonatomic) NSString *facePerceptionState;

@end

@implementation WZSignSettingController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpTableView];
    
    [self setUpData];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)setUpData {
    
    NSString *signType = [[NSUserDefaults standardUserDefaults] objectForKey:MOBILESIGN_TYPE];
    WZLog(@"signType = %@", signType);
    
    if ([signType isEqualToString:@"人脸识别"]) {
        self.signItemCount = 2;
    } else {
        self.signItemCount = 1;
    }
    
    BOOL iSFacePerpection = [[NSUserDefaults standardUserDefaults] boolForKey:@"facePerception_Key"];
    self.facePerceptionState = iSFacePerpection ? @"已认证" : @"未认证";
}


- (void)setUpTableView {
    
    self.view.backgroundColor = RGBCOLOR(238, 238, 238);
    self.tableView.rowHeight = 50;
    self.navigationItem.title = @"考勤设置";
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);
    self.tableView.backgroundColor = ClearColor;
}



#pragma mark -
#pragma mark tableView dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (0 == section) {
        return 1;
    }
    
    return self.signItemCount;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WZSignSettingCell *cell = [WZSignSettingCell signCellWithTableView:tableView];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//    cell.stateImgView.image = [UIImage imageNamed:@"80-80"];
    if (0 == indexPath.section) {
        cell.nameLabel.text = @"手机认证";
    } else {
        
        NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:MOBILESIGN_TYPE];
        
        if (!str) {
            switch (indexPath.row) {
                case 0:
                    cell.nameLabel.text = @"考勤方式";
                    cell.stateLabel.text = nil;
                    break;
                    
                case 1:
                    cell.nameLabel.text = @"人脸指纹";
                    cell.stateLabel.text = nil;
                    break;
                    
                default:
                    break;
            }
        } else {
            
            switch (indexPath.row) {
                case 0:
                    cell.nameLabel.text = @"考勤方式";
                    cell.stateLabel.text = str;
                    
                    if ([str isEqualToString:@"人脸识别"]) {
                        cell.stateImgView.image = [UIImage imageNamed:@"face_icon"];
                    }
                    
                    if ([str isEqualToString:@"指纹识别"]) {
                        cell.stateImgView.image = [UIImage imageNamed:@"finger_icon"];
                    }
                    
                    break;
                    
                case 1:
                    cell.nameLabel.text = [NSString stringWithFormat:@"%@认证", str];
                    cell.stateLabel.text = self.facePerceptionState;
                    if ([_facePerceptionState isEqualToString:@"已认证"]) {
                        cell.stateImgView.image = [UIImage imageNamed:@"sign_icon"];
                    } else {
                        cell.stateImgView.image = [UIImage imageNamed:@"uncertify_icon"];
                    }
                    break;
                    
                default:
                    break;
            }
        }
    }
    return cell;
}

#pragma mark -
#pragma mark delegate


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case 0:
            
            if (1 == indexPath.row) {
                // 手机认证
            }
            break;
            
        case 1:
            
            if (0 == indexPath.row) {
                
                [self setUpAlertView];
            }
            
            if (1 == indexPath.row) {
                
                WZFacePerceptionController *faceVc = [[WZFacePerceptionController alloc] init];
                [self.navigationController pushViewController:faceVc animated:YES];
            }
            
            break;
            
        default:
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (0 == section) {
        return CGFLOAT_MIN;
    }
    return 20;
}


#pragma mark -
#pragma mark alertView

- (void)setUpAlertView {
    
//    _signItemCount = 2;
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED <= __IPHONE_8_3
    NSString *faceBtn = @"人脸识别";
    NSString *fingerPrintBtn = @"指纹认证";
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"考勤方式" delegate:self
cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:faceBtn, fingerPrintBtn, nil];
    [actionSheet showInView:self.view];
    
//    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"考勤方式" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:faceBtn, fingerPrintBtn, nil];
//    
//    [alertView show];
    
#else
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:0];
    UIAlertAction *faceBtn = [UIAlertAction actionWithTitle:@"人脸识别" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _signType = @"人脸识别";
        _signItemCount = 2;
        [[NSUserDefaults standardUserDefaults] setObject:_signType forKey:MOBILESIGN_TYPE];
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:1];
        [_tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
    }];
    
    __weak typeof(self) weakSelf = self;
    UIAlertAction *fingerPrintBtn = [UIAlertAction actionWithTitle:@"指纹识别" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        // 判断指纹是否可用
        [weakSelf verificationFingerPrint];
        
    }];
    
    UIAlertAction *cancelBtn = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:fingerPrintBtn];
    [alert addAction:faceBtn];
    [alert addAction:cancelBtn];
    [self presentViewController:alert animated:YES completion:nil];
    
#endif

}

#pragma mark -
#pragma mark actionSheet delegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    _signType = @"人脸识别";
    _signItemCount = 2;
    [[NSUserDefaults standardUserDefaults] setObject:_signType forKey:MOBILESIGN_TYPE];
    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:0];
    [_tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationBottom];
}


- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    _signType = @"人脸识别";
    [[NSUserDefaults standardUserDefaults] setObject:_signType forKey:MOBILESIGN_TYPE];
    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:0];
    [_tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationBottom];
}


-(void)verificationFingerPrint {
    
    BOOL isSupport = [self isSupportfingerOfCurrentDuevice];
    
    if (!isSupport) {
        [MBProgressHUD showError:@"您的指纹识别不可用" toView:self.view];
        return;
    }
    
    BOOL ret = [USER_DEFAULT boolForKey:self.currentUser.UserName];
    if (!ret) {
        LAContext* context = [[LAContext alloc] init];
        context.localizedFallbackTitle = @"";
        NSString* result = @"请验证您的指纹以开启指纹支付";
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:result reply:^(BOOL success, NSError *error) {
            if (success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    // 设置指纹考勤方式
                    _signType = @"指纹识别";
                    _signItemCount = 1;
                    [[NSUserDefaults standardUserDefaults] setObject:_signType forKey:MOBILESIGN_TYPE];
                    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:1];
                    [_tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
                });
                
            } else {
                switch (error.code) {
                    case LAErrorSystemCancel:
                    {
                        NSLog(@"Authentication was cancelled by the system");
                        //切换到其他APP，系统取消验证Touch ID
                        break;
                    }
                    case LAErrorUserCancel:
                    {
                        NSLog(@"Authentication was cancelled by the user");
                        //用户取消验证Touch ID
                        break;
                    }
                    case LAErrorUserFallback:
                    {
                        NSLog(@"User selected to enter custom password");
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            //用户选择输入密码，切换主线程处理
                        }];
                        break;
                    }
                    default:
                    {
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            //其他情况，切换主线程处理
                        }];
                        break;
                    }
                }
            }
        }];
        
    } else {
        //
    }
}

//是否支持指纹
-(BOOL)isSupportfingerOfCurrentDuevice
{
    LAContext *context = [[LAContext alloc]init];
    BOOL ret = [context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:nil];
    return ret;
}


-(CContactModel *)currentUser
{
    if (_currentUser == nil) {
        _currentUser = [[[CContactMgr alloc]init] loadCurContact];
    }
    return _currentUser;
}


@end
